package com.example.user.customviewdemo.drawing.paint;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.example.user.customviewdemo.R;

/**
 * paint之ColorMatrix滤镜效果
 */
public class ColorMatrixActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener{
    private ImageView mImageView;
    private SeekBar mSeekBar;
    private Bitmap orgBitmap,tempBitmap;
    private ColorMatrix colorMatrix = new ColorMatrix();
    private Paint paint = new Paint();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_matrix);
        mImageView = (ImageView) findViewById(R.id.sta_imageview);
        mSeekBar = (SeekBar) findViewById(R.id.sta_seekbar);

        orgBitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.dog);
        //创建一个没有图像的、和orgBitmap等大小的bitmap
        tempBitmap = Bitmap.createBitmap(orgBitmap.getWidth(),orgBitmap.getHeight(), Bitmap.Config.ARGB_8888);

        mSeekBar.setMax(360);
        mSeekBar.setProgress(0);
        mSeekBar.setOnSeekBarChangeListener(this);

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        Bitmap bm = handleColorMatrix(i);
        mImageView.setImageBitmap(bm);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    /**
     * 通过progress对paint进行ColorMatrix操作，然后再把bitmap通过canvas绘制到tempBitmap上
     * @param progress
     * @return  滤镜后的bitmap
     */
    private Bitmap handleColorMatrix(int progress){
        /**
         * public void setSaturation(float sat)设置色彩饱和度
         *
         * public void setScale(float rScale, float gScale, float bScale,float aScale)将指定颜色放大倍数，默认为1
         *
         * public void setRotate(int axis, float degrees)；
                                  int axis：表示围绕哪个轴旋转，取值为0，1，2；
                                  取0时表示围绕红色轴旋转；
                                  取值1时，表示围绕绿色轴旋转；
                                  取值2时，表示围绕蓝色轴旋转；
                                  float degrees：表示旋转的度数
         *
         *
         */
        //colorMatrix.setSaturation(progress);//对色彩饱和度进行设置
        //colorMatrix.setScale(1,1.3f,1,1);//将绿色放大到1.3倍，所以狗脸以变绿
        colorMatrix.setRotate(0,progress);//对色彩进行旋转
        Canvas canvas = new Canvas(tempBitmap);//实例化一个以tempBitmap为背景的canvas画布
        paint.setAntiAlias(true);
        paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
        canvas.drawBitmap(orgBitmap,0,0,paint);//在画布从（0,0）位置画orgBitmap
        return tempBitmap;
    }
}
